<template>
	<base-page class="edit-form base-form" style="width: 100vw" title="学员报名" @back="onCancel">
		<view class="main-box">
			<view class="content-box">
				<u-form ref="mobileApplyInfoRef" :model="formData" label-width="120px" label-align="left"
					:errorType="['border-bottom', 'message']">
					<u-row gutter="0">
						<u-col :span="12">
							<view class="mt-16">
								<view class="u-cell-group" style="padding: 5px">
									<u-row gutter="0">
										<u-col :span="12">
											<field-input label="姓名" prop="StudentInfo.name"
												v-model="formData.StudentInfo.name" type="text" :clearable="true"
												:disabled="false" :required="true" :readonly="false" />
										</u-col>
										<u-col :span="12">
											<field-input label="手机号码" prop="StudentInfo.phone"
												v-model="formData.StudentInfo.phone" type="text" :clearable="true"
												:disabled="false" :required="true" :readonly="false" />
										</u-col>
										<u-col :span="12">
											<field-input label="身份证" prop="StudentInfo.identityCard"
												v-model="formData.StudentInfo.identityCard" type="text"
												:clearable="true" :disabled="false" :required="true"
												:readonly="false" />
										</u-col>
										<u-col :span="12">
											<field-select label="性别" prop="StudentInfo.sex"
												v-model="formData.StudentInfo.sex" :multiple="false"
												:dataList="MobileApplyInfo.sexWidget.dropdownList" :required="true"
												:disabled="false" />
										</u-col>
										<u-col :span="12">
											<field-select label="民族" prop="StudentInfo.nation"
												v-model="formData.StudentInfo.nation" :multiple="false"
												:dataList="MobileApplyInfo.nationWidget.dropdownList" :required="true"
												:disabled="false" />
										</u-col>
										<u-col :span="12">
											<field-input label="毕业学校" prop="StudentInfo.schooltag"
												v-model="formData.StudentInfo.schooltag" type="text" :clearable="true"
												:disabled="false" :required="false" :readonly="false" />
										</u-col>
										<u-col :span="12">
											<field-select label="学历" prop="StudentInfo.education"
												v-model="formData.StudentInfo.education" :multiple="false"
												:dataList="MobileApplyInfo.educationWidget.dropdownList"
												:required="true" :disabled="false" />
										</u-col>
										<u-col :span="12">
											<field-input label="教学课" prop="StudentInfo.teachSubjects"
												v-model="formData.StudentInfo.teachSubjects" type="text"
												:clearable="true" :disabled="false" :required="false"
												:readonly="false" />
										</u-col>
										<u-col :span="12">
											<field-input label="职称" prop="StudentInfo.professionalTitle"
												v-model="formData.StudentInfo.professionalTitle" type="text"
												:clearable="true" :disabled="false" :required="false"
												:readonly="false" />
										</u-col>
										<u-col :span="12">
											<field-select label="单位学校" prop="StudentInfo.schoolId"
												v-model="formData.StudentInfo.schoolId" :multiple="false"
												:dataList="MobileApplyInfo.schoolIdWidget.dropdownList" :required="true"
												:disabled="false" />
										</u-col>
										<u-col :span="12">
											<field-select label="班级" prop="StudentInfo.classId"
												v-model="formData.StudentInfo.classId" :multiple="false"
												:dataList="MobileApplyInfo.classIdWidget.dropdownList" :required="true"
												:disabled="false" />
										</u-col>
										<u-col :span="12">
											<field-calendar label="出生年月" prop="StudentInfo.dateOfBirth"
												v-model="formData.StudentInfo.dateOfBirth" color="#ee0a24"
												:required="true" :disabled="false" />
										</u-col>
										<u-col :span="12">
											<field-input label="籍贯" prop="StudentInfo.nativePlace"
												v-model="formData.StudentInfo.nativePlace" type="text" :clearable="true"
												:disabled="false" :required="true" :readonly="false" />
										</u-col>
										<u-col :span="12">
											<field-input label="政治面貌" prop="StudentInfo.partyGroupings"
												v-model="formData.StudentInfo.partyGroupings" type="text"
												:clearable="true" :disabled="false" :required="true"
												:readonly="false" />
										</u-col>
										<u-col :span="12">
											<field-input label="职务" prop="StudentInfo.jobTitle"
												v-model="formData.StudentInfo.jobTitle" type="text" :clearable="true"
												:disabled="false" :required="true" :readonly="false" />
										</u-col>
										<u-col :span="12">
											<field-calendar label="任职时间" prop="StudentInfo.jobTime"
												v-model="formData.StudentInfo.jobTime" color="#ee0a24" :required="true"
												:disabled="false" />
										</u-col>
										<u-col :span="12">
											<field-input label="进修编号" prop="StudentInfo.refresherCourseCode"
												v-model="formData.StudentInfo.refresherCourseCode" type="text"
												:clearable="true" :disabled="false" :required="false"
												:readonly="false" />
										</u-col>
										<u-col :span="12">
											<field-upload ref="photograph" label="照片" :required="true"
												prop="StudentInfo.photograph" v-model="formData.StudentInfo.photograph"
												:action="getUploadActionUrl('/admin/mobile/mobileEntry/uploadImage')"
												name="uploadFile" :header="getUploadHeaders" @input="onUploadSuccess"
												:file-list="fileList"
												:formData="{fieldName: 'photograph', asImage: false}"
												:downloadParams="{id: formData.StudentInfo.id, fieldName: 'photograph', asImage: false}"
												:maxCount="1" :disabled="false" :isImage="true" />
										</u-col>
									</u-row>
								</view>
							</view>
						</u-col>
					</u-row>
				</u-form>
			</view>
		</view>
		<view class="menu-box">
			<u-button type="default" size="medium" @click="onCancel()">取消</u-button>
			<u-button :custom-style="{width: '100%'}" style="flex-grow: 1; margin-left: 8px" type="primary"
				size="medium" @click="onAddClick()">
				提交
			</u-button>
		</view>
	</base-page>
</template>

<script>
	/* eslint-disable-next-line */
	import rules from '@/utils/validate';
	import {
		stringCase,
		treeDataTranslate,
		findItemFromList,
		findTreeNodePath,
		findTreeNode,
		showConfirm,
		showMessage,
		getToken
	} from '@/utils';

	import {
		uploadMixin,
		statsDateRangeMixin
	} from '@/utils/mixins';
	import {
		DropdownWidget,
		TableWidget,
		UploadWidget,
		ChartWidget
	} from '@/utils/widget.js';
	import {
		SysUserController,
		SchoolInfoController,
		ClassInfoController,
		StudentInfoController,
		DictionaryController
	} from '@/api';
	import projectConfig from '@/core/config'
	export default {
		name: 'mobileApplyInfo',
		props: {
			id: {
				default: undefined
			},
			subPage: {
				type: [Number, String, Boolean],
				default: 0
			},
			// 是否在提交的时候保存数据，用于级联页面
			saveOnSubmit: {
				type: Boolean,
				default: true
			},
			// 级联页面数据
			rowData: {
				type: Object
			}
		},
		mixins: [uploadMixin, statsDateRangeMixin],
		data() {
			return {
				formData: {
					StudentInfo: {
						// id
						id: undefined,
						// 班级id
						classId: undefined,
						// 姓名
						name: undefined,
						// 手机号码
						phone: undefined,
						// 0 男 1女
						sex: undefined,
						// 身份证号码
						identityCard: undefined,
						// 民族
						nation: undefined,
						// 毕业学校
						schooltag: undefined,
						// 学历
						education: undefined,
						// 教学课
						teachSubjects: undefined,
						// 职称
						professionalTitle: undefined,
						// 单位名称
						companyName: undefined,
						// 出生年月
						dateOfBirth: undefined,
						// 单位学校id
						schoolId: undefined,
						// 籍贯
						nativePlace: undefined,
						// 党派
						partyGroupings: undefined,
						// 职务
						jobTitle: undefined,
						// 任职时间
						jobTime: undefined,
						// 进修编号
						refresherCourseCode: undefined,
						// 照片
						photograph: undefined,
						// 创造时间
						createTime: undefined,
						// 修改时间
						updateTime: undefined,
						// 修改用户id
						updateUserId: undefined,
						// 创建用户id
						createUserId: undefined,
						// 登录用户id
						userId: undefined,
						// 删除标记
						deletedFlag: undefined,
						// 审核标记
						status: undefined,
						sysUser: {
							// 用户Id
							userId: undefined,
							// 登录用户名
							loginName: undefined,
							// 用户密码
							password: undefined,
							// 用户部门Id
							deptId: undefined,
							// 用户显示名称
							showName: undefined,
							// 用户类型(0: 管理员 1: 系统管理用户 2: 系统业务用户)
							userType: undefined,
							// 用户头像的Url
							headImageUrl: undefined,
							// 用户状态(0: 正常 1: 锁定)
							userStatus: undefined,
							// 用户邮箱
							email: undefined,
							// 用户手机
							mobile: undefined,
							// 第三方授权用户信息，这里是sys_user_auth表的冗余，主要用于发消息的时候提升运行时效率。
							userAuthInfo: undefined,
							// 创建者Id
							createUserId: undefined,
							// 更新者Id
							updateUserId: undefined,
							// 创建时间
							createTime: undefined,
							// 更新时间
							updateTime: undefined,
							// 删除标记(1: 正常 -1: 已删除)
							deletedFlag: undefined
						},
						classInfo: {
							// id
							id: undefined,
							// 班级code
							code: undefined,
							// 班级名称
							className: undefined,
							// 班级期数
							classPeriods: undefined,
							// 创造时间
							createTime: undefined,
							// 班主任id
							teacherId: undefined,
							// 修改时间
							updateTime: undefined,
							// 修改用户id
							updateUserId: undefined,
							// 创建用户id
							createUserId: undefined,
							// 删除标记
							deletedFlag: undefined
						},
						schoolInfo: {
							// 学校id
							id: undefined,
							// 账号id
							userId: undefined,
							// 学校名称
							name: undefined,
							// 学校负责人名称
							responsiblePersonName: undefined,
							// 0 男 1女
							sex: undefined,
							// 职务
							jobTitle: undefined,
							// 任职时间
							jobTime: undefined,
							// 手机号码
							phone: undefined,
							// 学校级别：1幼稚园 2小学 3中学 4大学
							level: undefined,
							// 创建时间
							createTime: undefined,
							// 更新时间
							updateTime: undefined,
							// 备注
							remark: undefined,
							// 创建人
							createUserId: undefined,
							// 更新人
							updateUserId: undefined
						},
						isDatasourceInit: false
					}
				},
				MobileApplyInfo: {
					// 性别组件
					sexWidget: new DropdownWidget(this.loadSexDropdownList),
					// 民族组件
					nationWidget: new DropdownWidget(this.loadNationDropdownList),
					// 学历组件
					educationWidget: new DropdownWidget(this.loadEducationDropdownList),
					// 单位学校组件
					schoolIdWidget: new DropdownWidget(this.loadSchoolIdDropdownList),

					// 班级组件
					classIdWidget: new DropdownWidget(this.loadClassIdDropdownList),
					isInit: false
				},
				rules: {
					'StudentInfo.schoolId': [{
						required: true,
						message: '请输入单位学校',
						trigger: 'blur',
						transform: (value) => String(value)
					}],
					'StudentInfo.education': [{
						required: true,
						message: '请输入学历',
						trigger: 'blur',
						transform: (value) => String(value)
					}],
					'StudentInfo.schooltag': [],
					'StudentInfo.photograph': [{
						required: true,
						message: '请输入照片',
						trigger: 'blur',
						transform: (value) => String(value)
					}],
					'StudentInfo.nation': [{
						required: true,
						message: '请输入民族',
						trigger: 'blur',
						transform: (value) => String(value)
					}],
					'StudentInfo.refresherCourseCode': [],
					'StudentInfo.identityCard': [{
						required: true,
						message: '请输入身份证',
						trigger: 'blur',
						transform: (value) => String(value)
					}],
					'StudentInfo.jobTime': [{
						required: true,
						message: '请输入任职时间',
						trigger: 'blur',
						transform: (value) => String(value)
					}],
					'StudentInfo.sex': [{
						required: true,
						message: '请输入性别',
						trigger: 'blur',
						transform: (value) => String(value)
					}],
					'StudentInfo.classId': [{
						required: true,
						message: '请输入班级',
						trigger: 'blur',
						transform: (value) => String(value)
					}],
					'StudentInfo.jobTitle': [{
						required: true,
						message: '请输入职务',
						trigger: 'blur',
						transform: (value) => String(value)
					}],
					'StudentInfo.phone': [{
						required: true,
						message: '请输入手机号码',
						trigger: 'blur',
						transform: (value) => String(value)
					}],
					'StudentInfo.partyGroupings': [{
						required: true,
						message: '请输入政治面貌',
						trigger: 'blur',
						transform: (value) => String(value)
					}],
					'StudentInfo.nativePlace': [{
						required: true,
						message: '请输入籍贯',
						trigger: 'blur',
						transform: (value) => String(value)
					}],
					'StudentInfo.name': [{
						required: true,
						message: '请输入姓名',
						trigger: 'blur',
						transform: (value) => String(value)
					}],
					'StudentInfo.dateOfBirth': [{
						required: true,
						message: '请输入出生年月',
						trigger: 'blur',
						transform: (value) => String(value)
					}],
					'StudentInfo.professionalTitle': [],
					'StudentInfo.teachSubjects': [],

				},
				fileList: []

			}
		},
		computed() {},
		methods: {

			onUploadSuccess(data, index, fileList, name) {
				// console.log(this.getUploadFileUrl(JSON.parse(data)[0], JSON.parse(data)[0].filename))
				this.fileList.push({
					src: this.getUploadFileUrl(JSON.parse(data)[0], JSON.parse(data)[0].filename)
				})
				this.formData.StudentInfo.photograph = (data)
			},
			getUploadFileUrl(item, params) {

				if (item == null || item.downloadUri == null) {
					return null;
				} else {

					const query = {};
					query.Authorization = getToken();
					query.filename = params

					return this.buildGetUrl(item.downloadUri, query);
				}
			},

			buildGetUrl(actionName, params) {
				const queryString = this.objectToQueryString(params);
				if (actionName != null && actionName !== '') {
					if (actionName.substring(0, 1) === '/') actionName = actionName.substring(1);


					return (
						projectConfig.baseUrl + actionName + (queryString == null ? '' : '?' + queryString)
					);
				}
			},

			objectToQueryString(params) {
				if (params == null) {
					return null;
				} else {
					return Object.keys(params)
						.map(key => {
							if (params[key] !== undefined) {
								return `${key}=${params[key]}`;
							} else {
								return undefined;
							}
						})
						.filter(item => item != null)
						.join('&');
				}
			},
			onCancel() {
				if (this.subPage) {
					this.$emit('close');
				} else {
					uni.navigateBack();
				}
			},
			/**
			 * 提交
			 */
			onAddClick() {

				this.$refs.mobileApplyInfoRef.validate((valid) => {
					if (!valid) return;
					// 级联操作
					if (!this.saveOnSubmit) {
						let formData = {
							...this.formData.StudentInfo
						};
						formData.sexDictMap = findItemFromList(this.MobileApplyInfo.sexWidget.dropdownList,
							formData.sex, 'id');
						formData.nationDictMap = findItemFromList(this.MobileApplyInfo.nationWidget.dropdownList,
							formData.nation, 'id');
						formData.educationDictMap = findItemFromList(this.MobileApplyInfo.educationWidget
							.dropdownList, formData.education, 'id');
						formData.schoolIdDictMap = findItemFromList(this.MobileApplyInfo.schoolIdWidget
							.dropdownList, formData.schoolId, 'id');
						this.$emit('submit', formData);
						this.onCancel();
						return;
					}
					let params = {
						studentInfoDto: {
							userId: uni.getStorageSync('userId'),
							// userId: this.formData.StudentInfo.userId,
							classId: this.formData.StudentInfo.classId,
							schoolId: this.formData.StudentInfo.schoolId,
							status: this.formData.StudentInfo.status,
							name: this.formData.StudentInfo.name,
							phone: this.formData.StudentInfo.phone,
							sex: this.formData.StudentInfo.sex,
							identityCard: this.formData.StudentInfo.identityCard,
							nation: this.formData.StudentInfo.nation,
							schooltag: this.formData.StudentInfo.schooltag,
							education: this.formData.StudentInfo.education,
							teachSubjects: this.formData.StudentInfo.teachSubjects,
							professionalTitle: this.formData.StudentInfo.professionalTitle,
							companyName: this.formData.StudentInfo.companyName,
							dateOfBirth: this.formData.StudentInfo.dateOfBirth,
							nativePlace: this.formData.StudentInfo.nativePlace,
							partyGroupings: this.formData.StudentInfo.partyGroupings,
							jobTitle: this.formData.StudentInfo.jobTitle,
							jobTime: this.formData.StudentInfo.jobTime,
							refresherCourseCode: this.formData.StudentInfo.refresherCourseCode,
							photograph: this.formData.StudentInfo.photograph,
							createUserId: this.formData.StudentInfo.createUserId,
						}
					};

					showConfirm('是否确认提交报名').then(res => {
						let httpCall = this.isEdit ? StudentInfoController.update : StudentInfoController
							.add;
						httpCall(this, params).then(res => {
							showMessage('提交成功', 'success');
							this.$emit('submit');
							this.onCancel(true);
						}).catch(e => {});
					}).catch(e => {});
				});
			},
			loadStudentInfoData() {
				return new Promise((resolve, reject) => {
					if (!this.isEdit) {
						resolve();
						return;
					}
					if (!this.saveOnSubmit && this.rowData != null) {
						this.formData.StudentInfo = JSON.parse(JSON.stringify(this.rowData));
						resolve();
						return;
					}
					let params = {
						id: this.id
					};
					StudentInfoController.view(this, params).then(res => {
						this.formData.StudentInfo = {
							...res,
							isDatasourceInit: true
						};
						if (this.formData.StudentInfo.sysUser == null) {
							this.$set(this.formData.StudentInfo, 'sysUser', {
								userId: undefined,
								loginName: undefined,
								password: undefined,
								deptId: undefined,
								showName: undefined,
								userType: undefined,
								headImageUrl: undefined,
								userStatus: undefined,
								email: undefined,
								mobile: undefined,
								userAuthInfo: undefined,
								createUserId: undefined,
								updateUserId: undefined,
								createTime: undefined,
								updateTime: undefined,
								deletedFlag: undefined
							});
						}
						if (this.formData.StudentInfo.classInfo == null) {
							this.$set(this.formData.StudentInfo, 'classInfo', {
								id: undefined,
								code: undefined,
								className: undefined,
								classPeriods: undefined,
								createTime: undefined,
								teacherId: undefined,
								updateTime: undefined,
								updateUserId: undefined,
								createUserId: undefined,
								deletedFlag: undefined
							});
						}
						if (this.formData.StudentInfo.schoolInfo == null) {
							this.$set(this.formData.StudentInfo, 'schoolInfo', {
								id: undefined,
								userId: undefined,
								name: undefined,
								responsiblePersonName: undefined,
								sex: undefined,
								jobTitle: undefined,
								jobTime: undefined,
								phone: undefined,
								level: undefined,
								createTime: undefined,
								updateTime: undefined,
								remark: undefined,
								createUserId: undefined,
								updateUserId: undefined
							});
						}
						resolve();
					}).catch(e => {
						reject(e);
					});
				});
			},
			/**
			 * 性别下拉数据获取函数
			 */
			loadSexDropdownList() {
				return Promise.resolve(this.Sex.getList());
			},
			/**
			 * 民族下拉数据获取函数
			 */
			loadNationDropdownList() {
				return Promise.resolve(this.Nation.getList());
			},
			/**
			 * 学历下拉数据获取函数
			 */
			loadEducationDropdownList() {
				return Promise.resolve(this.Education.getList());
			},
			/**
			 * 单位学校下拉数据获取函数
			 */
			loadSchoolIdDropdownList() {
				return new Promise((resolve, reject) => {
					const params = {};
					DictionaryController.dictSchoolInfo(this, params).then(res => {

						resolve(res.getList());
					}).catch(e => {
						reject(e);
					});
				});
			},
			loadClassIdDropdownList() {
				return new Promise((resolve, reject) => {
					const params = {
						filter: {}
					};
					ClassInfoController.listDict(this, params).then(res => {
						resolve(res);
					}).catch(e => {
						reject(e);
					});
				});
			},
			//ClassInfoController
			onUploadError(e, file, fileList) {
				this.$message.error('文件上传失败');
			},
			onUploadLimit(files, fileList) {
				this.$message.error('已经超出最大上传个数限制');
			},
			formInit() {
				this.loadStudentInfoData().then(res => {
					this.MobileApplyInfo.sexWidget.onVisibleChange(true).catch(e => {});
					this.MobileApplyInfo.nationWidget.onVisibleChange(true).catch(e => {});
					this.MobileApplyInfo.educationWidget.onVisibleChange(true).catch(e => {});
					this.MobileApplyInfo.schoolIdWidget.onVisibleChange(true).catch(e => {});
					this.MobileApplyInfo.classIdWidget.onVisibleChange(true).catch(e => {});
				}).catch(e => {});
			}
		},
		computed: {
			isEdit() {
				if (!this.saveOnSubmit) {
					return this.rowData != null;
				} else {
					return this.id != null;
				}
			}
		},
		mounted() {
			this.formInit();
			if (this.$refs.mobileApplyInfoRef) this.$refs.mobileApplyInfoRef.setRules(this.rules);
		}
	};
</script>

<style scoped></style>